package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {

    private static Integer MONTH = 12;

    @Reference
    private MemberService memberService;

    @Reference
    private ReportService reportService;

    @Reference
    private SetmealService setmealService;

    /**
     * 会员数量折线图
     * @return
     */
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.add(calendar.MONTH,-MONTH);

            //'months" : [”2019.o1”，"2019.02”,”2019.03"，"2019.04"]
            //'memberCount" :[3，4，8,10]
            List<String> months = new ArrayList<>();
            //获取对应年月[yyyy-MM]
            for (int i = 0; i < MONTH; i++) {
                calendar.add(calendar.MONTH,1);
                String yearAndMonth = new SimpleDateFormat("yyyy-MM").format(calendar.getTime());
                months.add(yearAndMonth);
            }

            //获取对应年月[yyyy-MM]对应的会员数量
            List<Integer> memberCounts = memberService.findMemberCountByYearAndMonth(months);

            Map<String, Object> data = new HashMap<>();
            data.put("months",months);
            data.put("memberCount",memberCounts);

            return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    /**
     * 套餐占比饼状图
     * @return
     */
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        try {
            //setmealCount
            //查询[t_setmeal]和[t_order]表的[套餐名称]和[数量]
            List<Map> setmealCount = setmealService.getValueAndNameFromSetmeal();

            //setmealNames
            List<String> setmealNames = new ArrayList<>();
            for (Map<String,Object> map : setmealCount) {
                String name = (String) map.get("name");
                setmealNames.add(name);
            }

            //返回页面的data
            Map<String, Object> data = new HashMap<>();
            data.put("setmealCount",setmealCount);
            data.put("setmealNames",setmealNames);

            return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    /**
     * 运营数据统计
     * @return
     */
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() throws Exception {
        try {
            Map<String,Object> data = reportService.getBusinessReportData();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try {
            //获取表格数据
            Map<String,Object> data = reportService.getBusinessReportData();
            String reportDate = (String) data.get("reportDate");//日期
            Integer todayNewMember = (Integer) data.get("todayNewMember");//今日新增会员数
            Integer totalMember = (Integer) data.get("totalMember");//总会员数
            Integer thisWeekNewMember = (Integer) data.get("thisWeekNewMember");//本周新会员
            Integer thisMonthNewMember = (Integer) data.get("thisMonthNewMember");//本月新会员
            Integer todayOrderNumber = (Integer) data.get("todayOrderNumber");//今日预约数量
            Integer todayVisitsNumber = (Integer) data.get("todayVisitsNumber");//今日到诊数量
            Integer thisWeekOrderNumber = (Integer) data.get("thisWeekOrderNumber");//本周预约数量
            Integer thisWeekVisitsNumber = (Integer) data.get("thisWeekVisitsNumber");//本周到诊数量
            Integer thisMonthOrderNumber = (Integer) data.get("thisMonthOrderNumber");//本月预约数量
            Integer thisMonthVisitsNumber = (Integer) data.get("thisMonthVisitsNumber");//本月到诊数量
            List<Map<String,Object>> hotSetmeal = (List<Map<String, Object>>) data.get("hotSetmeal");//热门套餐


            //获取[表格]的绝对路径
            String templateRealPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            //获取内存中的表格对象
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(templateRealPath)));
            //获取[表格]的[扇区]
            XSSFSheet sheetAt = excel.getSheetAt(0);

            //[日期]reportDate
            XSSFRow row = sheetAt.getRow(2);//第3行
            XSSFCell cell = row.getCell(5);//第6列
            cell.setCellValue(reportDate);//置入值
            //[新增会员数]todayNewMember
            row = sheetAt.getRow(4);//第5行
            cell = row.getCell(5);//第6列
            cell.setCellValue(todayNewMember);//置入值
            //[总会员数]totalMember
            row = sheetAt.getRow(4);//第5行
            cell = row.getCell(7);//第8列
            cell.setCellValue(totalMember);//置入值
            //[本周新会员]thisWeekNewMember
            row = sheetAt.getRow(5);//第6行
            cell = row.getCell(5);//第6列
            cell.setCellValue(thisWeekNewMember);//置入值
            //[本月新会员]thisWeekNewMember
            row = sheetAt.getRow(5);//第6行
            cell = row.getCell(7);//第8列
            cell.setCellValue(thisMonthNewMember);//置入值
            //[今日预约数量]todayOrderNumber
            row = sheetAt.getRow(7);//第8行
            cell = row.getCell(5);//第6列
            cell.setCellValue(todayOrderNumber);//置入值
            //[今日到诊数量]todayVisitsNumber
            row = sheetAt.getRow(7);//第5行
            cell = row.getCell(7);//第8列
            cell.setCellValue(todayVisitsNumber);//置入值
            //[本周预约数量]thisWeekOrderNumber
            row = sheetAt.getRow(8);//第9行
            cell = row.getCell(5);//第6列
            cell.setCellValue(thisWeekOrderNumber);//置入值
            //[本周到诊数量]thisWeekVisitsNumber
            row = sheetAt.getRow(8);//第9行
            cell = row.getCell(7);//第8列
            cell.setCellValue(thisWeekVisitsNumber);//置入值
            //[本月预约数量]thisMonthOrderNumber
            row = sheetAt.getRow(9);//第10行
            cell = row.getCell(5);//第6列
            cell.setCellValue(thisMonthOrderNumber);//置入值
            //[本月到诊数量]thisMonthVisitsNumber
            row = sheetAt.getRow(9);//第10行
            cell = row.getCell(7);//第8列
            cell.setCellValue(thisMonthVisitsNumber);//置入值

            int rowInt = 12;//13行
            for (Map<String, Object> map : hotSetmeal) {
                String name = (String) map.get("name");//套餐名称
                Long setmeal_count = (Long) map.get("setmeal_count");//预约数量
                BigDecimal proportion = (BigDecimal) map.get("proportion");//占比
                //第四列,套餐名称
                sheetAt.getRow(rowInt).getCell(4).setCellValue(name);
                //第五列,预约数量
                sheetAt.getRow(rowInt).getCell(5).setCellValue(setmeal_count);
                //第六列,占比
                sheetAt.getRow(rowInt).getCell(6).setCellValue(proportion.doubleValue());
                rowInt++;
            }

            //通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            //设置请求头
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            excel.write(out);

            out.flush();
            out.close();
            excel.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL,null);
    }
    /*public static void main(String[] args) throws Exception{

    }*/
}
